using UnityEngine;
using System.Collections;

/**
 * Script of Replay recording.
 * The purpose of this class is to record transform datas.
 * @author Benjamin Bruneau
 */
public class ReplayRecorderScript : MonoBehaviour 
{
	private const string REPLAY_MODE_NAME = "ReplayMode"; // Replay Mode GameObject's name
	private const string BALL_NAME = "Ball"; // Main GameObject's name
	private const string SEPARATOR = ";"; // Data Separator
	
	private string _previousLine = ""; // Previous line
	private string _currentLine = ""; // Next line
	
	private GameObject _replayMode; // Replay mode GameObject
	
	public GameObject _inputStream; // Game camera GameObject

	/**
	 * Called on initialization.
	 * @return void
	 */
	void Start () 
	{
	
		//Initialized because this object moves through scenes
		_replayMode = GameObject.Find (REPLAY_MODE_NAME);
		
		// If replay mode
		if(_replayMode.GetComponent<ReplayModeScript>()._replayMode)
		{
			this.enabled = false;
		}
		
	}
	
	/**
	 * Called once per fixed frame.
	 * @return void
	 */
	void FixedUpdate () 
	{
	
		// If not in replay mode
		if(!_replayMode.GetComponent<ReplayModeScript>()._replayMode)
		{
		
			// If GameObject is a platform
			if(!this.gameObject.name.Equals(BALL_NAME))
			{
				// If the platform has enabled controls
				if(this.gameObject.GetComponent<ControllerScript>().enabled)
				{		
					write ();			
				}
				
			} else {	
				write ();		
			}	
		}
	}
	
	/**
	 * Saves current action performed.
	 * @return void
	 */
	private void write ()
	{
		_currentLine = saveFrame();
		
		// Writes it in string
		if(!_currentLine.Equals(_previousLine))
		{
			_inputStream.GetComponent<StreamWriterScript>().write(_currentLine);
			_previousLine = _currentLine;
		}
	}
	
	/**
	 * Saves current frame (transform component informations).
	 * @return string
	 */
	private string saveFrame()
	{
		
		string line = "";
		line = line + this.gameObject.name + SEPARATOR;
		line = line + this.gameObject.transform.position.x + SEPARATOR;
		line = line + this.gameObject.transform.position.y + SEPARATOR;
		line = line + this.gameObject.transform.position.z + SEPARATOR;
		line = line + this.gameObject.transform.rotation.x + SEPARATOR;
		line = line + this.gameObject.transform.rotation.y + SEPARATOR;
		line = line + this.gameObject.transform.rotation.z + SEPARATOR;
		line = line + this.gameObject.transform.rotation.w + SEPARATOR;
		
		return line;
	}
}
